namespace Sharpmark.PerfectLife.Core.HtmlDocument
{
    using System.Text;

    public class HtmlGenerator
    {
        protected StringBuilder _html;
        protected bool _isTagClosed;
        protected string _elementName; // for close the element

        protected HtmlGenerator(string name)
        {
            _html = new StringBuilder();
            _isTagClosed = false;
            _elementName = name;

            StartElement();
        }
        private void StartElement()
        {
            _html.Append("<");
            _html.Append(_elementName);
        }

        protected void NewAttribute(
            string attrName,
            string attrValue
            )
        {
            if (!_isTagClosed)
            {
                _html.Append(" ");
                _html.Append(attrName);
                _html.Append("=\"");
                _html.Append(attrValue);
                _html.Append("\"");
            }
        }

        protected void AppendContent(string content)
        {
            _isTagClosed = true;
            _html.Append(">");   //end start element
            _html.Append(content);
        }

        protected void CloseElement()
        {
            CloseElement(false);
        }

        protected void CloseElement(bool isNest)
        {
            if (_isTagClosed)
            {
                _html.Append("</");
                _html.Append(_elementName);
                _html.Append(">");
            }
            else
            {
                _html.Append("/>");
            }
            _isTagClosed = true;
        }

        public override string ToString()
        {
            return _html.ToString();
        }
    }
}
